package com.softeem.xyblogmaster.handler;

import cn.hutool.json.JSONUtil;
import com.softeem.xyblogmaster.exception.ServiceException;
import com.softeem.xyblogmaster.util.AjaxResult;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.security.SignatureException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler({ServiceException.class})
    @ResponseBody
    public AjaxResult  serviceExceptionHandler(Exception e){
        String message = e.getMessage();
        if(message.contains("-")){
            String[] split = message.split("-");
            int code=Integer.parseInt(split[0]);
            String msg=split[1];
            return AjaxResult.fail(code,msg);
        }
        else{
            return AjaxResult.fail(message);
        }

    }



    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public AjaxResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<String> messageList = new ArrayList<>();
        if (e.hasErrors()) {

            List<FieldError> fieldErrors = e.getFieldErrors();
            //迭代错误
            fieldErrors.forEach((fieldError) -> {
                //哪个属性出错
                //String field = fieldError.getField();
                //传递过来什么数据
                //Object rejectedValue = fieldError.getRejectedValue();
                //报了什么错误
                String message = fieldError.getDefaultMessage();
                messageList.add(message);
            });
        }
        return  AjaxResult.fail(400, JSONUtil.toJsonStr(messageList));
    }
}
